package com.junqson.je.content.util;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.junqson.je.common.exception.BizException;
import com.junqson.je.common.model.ApiResult;
import com.junqson.je.common.model.vo.SimpleUserInfo;
import com.junqson.je.content.client.UserClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.LinkedHashMap;
import java.util.concurrent.TimeUnit;

/**
 * @Descriptions
 * @Company
 * @Author Junqson
 * @Date 2020/2/6 12:21
 * @Version 1.0
 */
@Component
public class UserInfoCache {

    @Autowired
    UserClient userClient;

    /**
     * 缓存请求的userinfo
     */
    LoadingCache<String, SimpleUserInfo> userInfoCache = CacheBuilder.newBuilder()
            .maximumSize(200)
            .expireAfterWrite(60, TimeUnit.SECONDS)
            .build(
                    new CacheLoader<String, SimpleUserInfo>() {
                        @Override
                        public SimpleUserInfo load(String key) {
                            ApiResult result = userClient.userInfo(Integer.valueOf(key));
                            if (result.isSuccess()) {
                                System.out.println(result.getData() instanceof LinkedHashMap);
                                return (SimpleUserInfo) result.getData();
                            } else {
                                throw new BizException("fetch user info failed");
                            }
                        }
                    }
            );

    public SimpleUserInfo getUserInfo(Integer userId) {
        String k = userId.toString();
        return userInfoCache.getUnchecked(k);
    }
}
